<template>
    <el-dialog title="生产指令详情" :visible.sync="visible" width="900px" append-to-body @close="handleClose"
        :custom-class="'instruction-detail-dialog'" :show-close="true" top="30px">
        <div class="dialog-content">
            <div class="detail-header">
                <div class="header-left">
                    <span class="header-tag">指令编号</span>
                    <span class="header-code">{{ orderCode }}</span>
                </div>
                <div class="header-right">
                    <span class="update-time">加载时间：{{ formatCurrentTime() }}</span>
                </div>
            </div>

            <!-- 指令列表：每条指令对应一个折叠面板 -->
            <div class="instruction-list" v-loading="loading">
                <el-collapse accordion>
                    <el-collapse-item v-for="(instruction, idx) in instructionList" :key="idx"
                        :title="`指令：${instruction.orderCode} - ${instruction.orderName}`" class="instruction-collapse">
                        <div class="instruction-info">
                            <!-- 指令基础信息 -->
                            <el-form :model="instruction" label-width="120px" size="mini" class="instruction-form">
                                <el-form-item label="所属产业">
                                    <span>{{ instruction.gmpIndustry || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="产品名称">
                                    <span>{{ instruction.productName || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="产品编码">
                                    <span>{{ instruction.productCode || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="产品规格">
                                    <span>{{ instruction.spec || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="计划产量">
                                    <span>{{ instruction.plannedOutput || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="房间编号">
                                    <span>{{ instruction.roomCode || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="审批人">
                                    <span>{{ instruction.approver || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="审批日期">
                                    <span>{{ parseTime(instruction.approveDate, '{y}-{m}-{d} {h}:{i}') || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="物料编码">
                                    <span>{{ instruction.productionMaterialCode || '-' }}</span>
                                </el-form-item>
                                <el-form-item label="附件">
                                    <el-link v-if="instruction.contentUrl" :href="instruction.contentUrl"
                                        target="_blank" class="download-link" :underline="false">
                                        <i class="el-icon-download el-icon--left"></i>下载
                                    </el-link>
                                    <span v-else>-</span>
                                </el-form-item>
                            </el-form>

                            <!-- 关联物料表格：独立展示多条物料 -->
                            <div class="material-table-container" v-if="instruction.materialList.length > 0">
                                <h4 class="material-title">关联物料信息（{{ instruction.materialList.length }}条）</h4>
                                <el-table :data="instruction.materialList" size="mini" border style="width: 100%" stripe
                                    :header-cell-style="{
                                        'background-color': '#eef1f6',
                                        'color': '#333',
                                        'font-weight': '500',
                                        'text-align': 'center'
                                    }" :cell-style="{
                                        'text-align': 'center'
                                    }" @cell-click="(row) => openMaterialDetail(row)">
                                    <el-table-column prop="materialCode" label="物料编码" width="140" align="center" />
                                    <el-table-column prop="materialName" label="物料名称" width="120" align="center" />
                                    <el-table-column prop="specification" label="物料规格" width="100" align="center" />
                                    <el-table-column prop="supplier" label="供应商" width="140" align="center" />
                                    <el-table-column prop="productionDate" label="生产日期" width="140" align="center" />
                                    <el-table-column prop="expirationDate" label="有效期至" width="140" align="center" />
                                    <el-table-column prop="storageCondition" label="储存条件" width="120" align="center" />
                                    <el-table-column prop="qualifiedQuantity" label="合格数量" width="100" align="center" />
                                </el-table>
                            </div>
                            <div class="no-material" v-else>
                                暂无关联物料信息（指令物料编码：{{ instruction.productionMaterialCode || '无' }}）
                            </div>
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </div>

            <!-- 物料详情弹窗 -->
            <el-dialog title="物料详情" :visible.sync="materialDialogVisible" width="600px" append-to-body>
                <div v-if="currentMaterial" class="material-detail">
                    <el-form :model="currentMaterial" label-width="120px" size="mini">
                        <el-form-item label="物料编码">
                            <span>{{ currentMaterial.materialCode }}</span>
                        </el-form-item>
                        <el-form-item label="物料名称">
                            <span>{{ currentMaterial.materialName }}</span>
                        </el-form-item>
                        <el-form-item label="供应商">
                            <span>{{ currentMaterial.supplier }}</span>
                        </el-form-item>
                        <el-form-item label="生产厂家">
                            <span>{{ currentMaterial.manufacturer }}</span>
                        </el-form-item>
                        <el-form-item label="厂家批号">
                            <span>{{ currentMaterial.manufacturerBatchNumber }}</span>
                        </el-form-item>
                        <el-form-item label="生产日期">
                            <span>{{ currentMaterial.productionDate }}</span>
                        </el-form-item>
                        <el-form-item label="有效期至">
                            <span>{{ currentMaterial.expirationDate }}</span>
                        </el-form-item>
                        <el-form-item label="储存条件">
                            <span>{{ currentMaterial.storageCondition }}</span>
                        </el-form-item>
                        <el-form-item label="规格">
                            <span>{{ currentMaterial.specification }}</span>
                        </el-form-item>
                        <el-form-item label="接收数量">
                            <span>{{ currentMaterial.receivedQuantity }}</span>
                        </el-form-item>
                        <el-form-item label="合格数量">
                            <span>{{ currentMaterial.qualifiedQuantity }}</span>
                        </el-form-item>
                        <el-form-item label="接收人">
                            <span>{{ currentMaterial.receiver }}</span>
                        </el-form-item>
                    </el-form>
                </div>
                <div v-else class="empty-material">暂无物料详情数据</div>
                <div slot="footer" class="material-dialog-footer">
                    <el-button type="primary" size="mini" @click="materialDialogVisible = false">关闭</el-button>
                </div>
            </el-dialog>
        </div>

        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="handleClose" class="close-btn">
                关闭
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getOrderByCode } from '@/api/product/order'
import { getMaterialByCode } from '@/api/material/MaterialRecord'

export default {
    name: 'InstructionDetailDialog',
    data() {
        return {
            visible: false,
            loading: false,
            orderCode: '',
            instructionList: [], // 指令列表（每条包含自身信息+关联物料列表）
            materialDialogVisible: false,
            currentMaterial: null
        }
    },
    methods: {
        show(orderCode) {
            this.orderCode = orderCode || '未知编号'
            this.visible = true
            this.loadData()
        },

        async loadData() {
            this.loading = true
            try {
                // 1. 获取指令数据
                const orderRes = await getOrderByCode(this.orderCode)
                const orderData = Array.isArray(orderRes.data) ? orderRes.data : (orderRes.data ? [orderRes.data] : [])

                // 2. 提取所有物料编码（支持逗号分隔的多个编码）
                let allMaterialCodes = []
                orderData.forEach(item => {
                    if (item.productionMaterialCode) {
                        // 拆分逗号分隔的编码，去空格+去重
                        const codes = item.productionMaterialCode
                            .split(',')
                            .map(code => code.trim())
                            .filter(Boolean)
                        allMaterialCodes = [...allMaterialCodes, ...codes]
                    }
                })
                allMaterialCodes = [...new Set(allMaterialCodes)] // 最终去重
                console.log('最终待查询的物料编码：', allMaterialCodes)

                // 3. 批量查询物料信息
                const materialMap = {}
                if (allMaterialCodes.length > 0) {
                    const materialRes = await getMaterialByCode(allMaterialCodes.join(','))
                    const materialList = materialRes.data || []
                    // 构建映射表：单个编码对应多个物料
                    materialList.forEach(material => {
                        const key = (material.materialCode || '').trim().toUpperCase()
                        if (!materialMap[key]) {
                            materialMap[key] = []
                        }
                        materialMap[key].push(material)
                    })
                }

                // 4. 关联物料到指令（拆分多编码分别匹配）
                this.instructionList = orderData.map(instruction => {
                    let matchedMaterials = []
                    if (instruction.productionMaterialCode) {
                        // 拆分当前指令的多个物料编码
                        const orderCodes = instruction.productionMaterialCode
                            .split(',')
                            .map(code => code.trim().toUpperCase())
                            .filter(Boolean)
                        // 逐个匹配并合并结果
                        orderCodes.forEach(code => {
                            matchedMaterials = [...matchedMaterials, ...(materialMap[code] || [])]
                        })
                    }
                    return {
                        ...instruction,
                        materialList: matchedMaterials
                    }
                })

            } catch (err) {
                console.error('数据加载失败：', err)
                this.$message.error(`数据加载失败：${err.message || '未知错误'}`)
                this.instructionList = []
            } finally {
                this.loading = false
            }
        },

        // 打开物料详情弹窗
        openMaterialDetail(material) {
            this.currentMaterial = material
            this.materialDialogVisible = true
        },

        handleClose() {
            this.visible = false
            this.instructionList = []
            this.orderCode = ''
            this.materialDialogVisible = false
            this.currentMaterial = null
        },

        formatCurrentTime() {
            const date = new Date()
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hour = String(date.getHours()).padStart(2, '0')
            const minute = String(date.getMinutes()).padStart(2, '0')
            return `${year}-${month}-${day} ${hour}:${minute}`
        },

        parseTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
            if (!time) return ''
            const date = new Date(time)
            const formatObj = {
                y: date.getFullYear(),
                m: date.getMonth() + 1,
                d: date.getDate(),
                h: date.getHours(),
                i: date.getMinutes(),
                s: date.getSeconds()
            }
            return format.replace(/{([ymdhsi])+}/g, (result, key) => {
                const value = formatObj[key]
                return value.toString().padStart(2, '0')
            })
        }
    }
}
</script>

<style scoped>
.instruction-detail-dialog {
    border-radius: 8px !important;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
    border: 1px solid #ebeef5 !important;
}

.dialog-content {
    padding: 16px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e6ebf5;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-tag {
    background-color: #e6f7ff;
    color: #1890ff;
    font-size: 12px;
    padding: 3px 8px;
    border-radius: 4px;
}

.header-code {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.header-right .update-time {
    font-size: 12px;
    color: #999;
}

/* 指令折叠面板样式 */
.instruction-list {
    border-radius: 6px;
    overflow: hidden;
}

.instruction-collapse {
    border: 1px solid #ebeef5;
    border-radius: 6px;
    margin-bottom: 12px;
}

.el-collapse-item__header {
    background-color: #f5f7fa !important;
    font-weight: 500 !important;
}

/* 指令信息表单样式 */
.instruction-info {
    padding: 16px;
}

.instruction-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f2f5;
}

.instruction-form .el-form-item {
    margin-bottom: 0;
    width: calc(33.33% - 12px);
}

/* 物料表格样式 */
.material-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
}

.material-table-container {
    margin-top: 16px;
}

/* 无物料提示样式 */
.no-material {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 12px;
}

/* 物料详情弹窗样式 */
.material-detail {
    padding: 10px 0;
}

.el-form-item {
    margin-bottom: 12px;
}

.empty-material {
    text-align: center;
    padding: 30px 0;
    color: #999;
}

.material-dialog-footer {
    display: flex;
    justify-content: center;
    padding: 10px 0;
}

/* 底部按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: center;
    padding: 12px 0;
}

.close-btn {
    width: 100px;
}

/* 下载链接样式 */
.download-link {
    color: #1890ff;
    font-size: 12px;
    transition: color 0.2s;
}

.download-link:hover {
    color: #096dd9;
}
</style>